<?php 
class chatClassAction extends ActionManage
{
	public function defaultAction()
	{
		$type = $this->get('type');
		$this->assign('type', $type);
	}
	

	public function dataAction()
	{
		$sort = $this->get('sort');
		$dir  = $this->get('dir');
		$order= '`sort` asc';
		if($sort && $dir)$order= '`'.$sort.'` '.$dir.'';
		$dbs   = m('chatgroup');
		$rows  = $dbs->getall('`cid`='.$this->companyid.'','*', $order);
		foreach($rows as $k=>$rs)$rows[$k]['picurl'] = getface($rs['picurl'], $dbs->defpic);
		
		$barr  = array(
			'rows' => $rows,
			'success' => true,
		);
		return $barr;
	}
	
	public function formAction()
	{	
		$id = (int)$this->get('id','0');
		$this->smartydata['id'] = $id;
			
		$fields = c('fields')->getArr('chatgroup');
		$rs 	= $fields['data'];
		$fobj 	= $fields['fieldsobj'];
		
		$dbs   = m('chatgroup');
		
		if($id>0){
			$rs 	= m('chatgroup')->getone('`id`='.$id.'');
			if(!isempt($rs['picurl']))$rs['picurlpic'] = getface($rs['picurl'], $dbs->defpic);
		}else{
			$rs['createid'] 	= $this->useraid;
			$rs['createname'] 	= $this->userainfo['name'];
		}
		
		if(isempt(arrvalue($rs,'picurlpic')))$rs['picurlpic'] = $dbs->defpic;

		$this->assign('fieldsobj', $fobj);
		$this->assign('data', $rs);
	}
	
	public function savecheckAction()
	{
		
		$id = (int)$this->post('id','0');
		$name= $this->post('name');
		if(isempt($name))return '名称不能为空';
		
		$db = m('chatgroup');
		
		$uarr= array(
			'name' 		=> $name,
			'cid' 		=> $this->companyid,
			'picurl' 	=> $this->post('picurl'),
			'recename' 	=> $this->post('recename'),
			'receid' 	=> $this->post('receid'),
			'createname' 	=> $this->post('createname'),
			'sort' 		=> (int)$this->post('sort','0'),
			'createid' 	=> (int)$this->post('createid','0')
		);
		$where = '`id`='.$id.' and `cid`='.$this->companyid.'';
		if($id==0){
			$where = '';
			$uarr['createdt'] 	= $this->now;
			$uarr['num'] = $this->db->ranknum('[Q]chatgroup','num',8);
		}
		$bo 	= $db->record($uarr, $where);
		if(!$bo)return $this->db->error();
		if($id==0)$id = $this->db->insert_id();
		if(isempt($uarr['receid'])){
			$db->adduser($id, $uarr['createid'],0,$this->companyid);
		}
		$db->reloaduser($id);
		
		return 'ok';
	}
	
	public function delchatAction()
	{
		$id = (int)$this->post('id','0');
		if($id<1)return returnerror('无效ID');
		m('chatgroup')->delete('`id`='.$id.' and `cid`='.$this->companyid.'');
		m('chatgroupuser')->delete('`gid`='.$id.'');
		
		return returnsuccess();
	}
}